<?php

namespace App\Http\Controllers\H5;
use App\Common\ResponseCode;
use App\Http\Controllers\BaseController;
use App\Params\H5\AddressUpdateParams;
use App\Services\Customer\AddressService;
use App\Traits\VerifyRequestParam;
use Illuminate\Http\Request;

/**
 * 地址相关控制器
 *
 * @author WangBin
 * @date 2021-09-17
 * @package App\Http\Controllers\H5
 */
class AddressController extends BaseController
{
    use VerifyRequestParam;

    /**
     * 获取客户收货地址列表
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\BusinessException
     */
    public function getList()
    {
        $filter = ['customer_id' => $this->verifyInteger('customer_id')];
        $addressList = AddressService::getInstance()->getList($filter);
        return $this->success($addressList);
    }

    /**
     * 获取地址信息
     *
     * @throws
     * @return \Illuminate\Http\JsonResponse
     */
    public function get()
    {
        $addressId = $this->verifyInteger('address_id');
        $address = AddressService::getInstance()->get($addressId);
        if(empty($address)) {
            $this->fail(ResponseCode::ADDRESS_NOT_FOUND);
        }
        return $this->success($address);
    }

    /**
     * 删除客户地址
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        $addressId = $request->input('address_id');
        $customerId = $request->attributes->get('customer_id');
        if (empty($addressId) || empty($customerId)) {
            return $this->fail(ResponseCode::PARAM_ILLEGAL);
        }
        $ret = AddressService::getInstance()->delete($addressId, $customerId);
        if(!$ret) {
            return $this->fail(ResponseCode::OP_FAIL);
        }
        return $this->success(ResponseCode::ADDRESS_DEL_SUCCESS);
    }

    /**
     * 设置默认地址
     *
     * @throws
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDefault()
    {
        $addressId = $this->verifyInteger('address_id');
        $customerId = $this->verifyInteger('customer_id');
        $ret = AddressService::getInstance()->setDefault($addressId, $customerId);
        if(!$ret) {
            return $this->fail(ResponseCode::OP_FAIL);
        }
        return $this->success();
    }

    /**
     * 保存收货地址
     *
     * @throws \App\Exceptions\BusinessException
     * @return
     */
    public function update()
    {
        $param = AddressUpdateParams::create();
        $addressId = AddressService::getInstance()->update($param);
        return $this->success($addressId);
    }

    /**
     * 获取客户默认收货地址
     *
     * @throws
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDefault()
    {
        $addressId = AddressService::getInstance()->getDefault($this->verifyInteger('customer_id'));
        return $this->success(['default_id' => $addressId]);
    }
}
